﻿namespace LivePatterns
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Reflection;
	using System.Reflection.Emit;

	public static partial class Build
	{
		/// <summary>
		/// Disables specified methods on an instance.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="obj">The actual instance to create a proxy from.</param>
		/// <param name="disabledMethods">Methods to disable.</param>
		/// <returns>Returns a proxy instance that does not allow to invoke the specified methods.</returns>
		public static T Disable<T>(T obj, IEnumerable<MethodBase> disabledMethods) where T : class
		{
			if (!typeof(T).IsInterface)
				throw new ArgumentException("Only interface types are supported.");

			if (obj == null)
				throw new ArgumentNullException("obj");

			if (disabledMethods == null)
				throw new ArgumentNullException("methods");

			if (!disabledMethods.Any())
				return obj;

			const string errorMessage = "The requested operation is not allowed on this instance.";

			TypeBuilder typeBuilder = moduleBuilder.DefineType(String.Format("{0}_Disabled_{1}", typeof(T).Name, Guid.NewGuid().ToString().Replace("-", "")), TypeAttributes.Class | TypeAttributes.Public);
			typeBuilder.AddInterfaceImplementation(typeof(T));

			// create a field for storing the real object instance
			FieldBuilder inner = typeBuilder.DefineField("innerObject", typeof(T), FieldAttributes.Family);

			// create a construtor, in which we can pass the real object instance
			ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(T) });
			ILGenerator cilg = constructorBuilder.GetILGenerator();
			cilg.ConstructObject();
			cilg.Emit(OpCodes.Ldarg_0);
			cilg.Emit(OpCodes.Ldarg_1);
			cilg.Emit(OpCodes.Stfld, inner);

			// implement fields
			foreach (FieldInfo fi in typeof(T).GetFields(BindingFlags.Public | BindingFlags.Instance).Where(m => !m.IsSpecialName))
			{
				FieldBuilder fb = typeBuilder.DefineField(fi.Name, fi.FieldType, FieldAttributes.Public);

				// build constructor
				cilg.Emit(OpCodes.Ldarg_0);
				cilg.Emit(OpCodes.Ldarg_1);
				cilg.Emit(OpCodes.Ldfld, fi);
				cilg.Emit(OpCodes.Stfld, fb);
			}

			cilg.Return();

			// implement properties
			foreach (PropertyInfo pi in typeof(T).GetAllVisibleProperties())
			{
				// define property
				PropertyBuilder pb = typeBuilder.DefineProperty(pi.Name, PropertyAttributes.None, typeof(int), Type.EmptyTypes);
				MethodBuilder methodBuilder;
				ILGenerator ilGenerator;

				//
				// implement get method
				//
				if (pi.CanRead)
				{
					MethodInfo getMethod = pi.GetGetMethod();
					methodBuilder = typeBuilder.DefineMethod(
						getMethod.Name, _methodAttributes, pi.PropertyType, getMethod.GetParameters().Select(p => p.ParameterType).ToArray()
					);

					ilGenerator = methodBuilder.GetILGenerator();
					if (!disabledMethods.Contains(getMethod))
					{
						ilGenerator.Emit(OpCodes.Ldarg_0);
						ilGenerator.Emit(OpCodes.Ldfld, inner);
						ilGenerator.Emit(OpCodes.Call, getMethod);
						ilGenerator.Return();
					}
					else
						ilGenerator.ThrowException(typeof(InvalidOperationException), errorMessage);
					pb.SetGetMethod(methodBuilder);
				}

				//
				// implement set method
				//
				if (pi.CanWrite)
				{
					MethodInfo setMethod = pi.GetSetMethod();
					methodBuilder = typeBuilder.DefineMethod(
						setMethod.Name, _methodAttributes, setMethod.ReturnType, setMethod.GetParameters().Select(p => p.ParameterType).ToArray()
					);
					methodBuilder.DefineParameter(1, ParameterAttributes.None, "value");

					ilGenerator = methodBuilder.GetILGenerator();
					if (!disabledMethods.Contains(setMethod))
					{
						ilGenerator.Emit(OpCodes.Ldarg_0);
						ilGenerator.Emit(OpCodes.Ldfld, inner);
						ilGenerator.Emit(OpCodes.Ldarg_1);
						ilGenerator.Emit(OpCodes.Call, setMethod);
						ilGenerator.Return();
					}
					else
						ilGenerator.ThrowException(typeof(InvalidOperationException), errorMessage);
					pb.SetSetMethod(methodBuilder);
				}
			}

			// implement methods
			foreach (MethodInfo mi in typeof(T).GetAllVisibleMethods())
			{
				MethodBuilder methodBuilder = typeBuilder.DefineMethod(
					mi.Name, MethodAttributes.Public | MethodAttributes.Virtual, mi.ReturnType, mi.GetParameters().Select(p => p.ParameterType).ToArray()
				);

				ILGenerator ilGenerator = methodBuilder.GetILGenerator();
				if (!disabledMethods.Contains(mi))
				{
					ilGenerator.Emit(OpCodes.Ldarg_0);
					ilGenerator.Emit(OpCodes.Ldfld, inner);
					ilGenerator.LoadAllArguments(mi);
					ilGenerator.Emit(OpCodes.Callvirt, mi);
					ilGenerator.Return();
				}
				else
					ilGenerator.ThrowException(typeof(InvalidOperationException), errorMessage);
			}

			// implement events
			foreach (EventInfo ei in typeof(T).GetAllVisibleEvents())
			{
				// define event
				EventBuilder eb = typeBuilder.DefineEvent(ei.Name, EventAttributes.None, ei.EventHandlerType);
				MethodBuilder methodBuilder;
				ILGenerator ilGenerator;

				//
				// implement add method
				//
				MethodInfo addMethod = ei.GetAddMethod();
				methodBuilder = typeBuilder.DefineMethod(
					addMethod.Name, _methodAttributes, addMethod.ReturnType, addMethod.GetParameters().Select(p => p.ParameterType).ToArray()
				);

				ilGenerator = methodBuilder.GetILGenerator();
				if (!disabledMethods.Contains(addMethod))
				{
					ilGenerator.Emit(OpCodes.Ldarg_0);
					ilGenerator.Emit(OpCodes.Ldfld, inner);
					ilGenerator.Emit(OpCodes.Ldarg_1);
					ilGenerator.Emit(OpCodes.Callvirt, addMethod);
					ilGenerator.Return();
				}
				else
					ilGenerator.ThrowException(typeof(InvalidOperationException), errorMessage);
				eb.SetAddOnMethod(methodBuilder);

				//
				// implement remove method
				//
				MethodInfo removeMethod = ei.GetRemoveMethod();
				methodBuilder = typeBuilder.DefineMethod(
					removeMethod.Name, _methodAttributes, removeMethod.ReturnType, removeMethod.GetParameters().Select(p => p.ParameterType).ToArray()
				);

				ilGenerator = methodBuilder.GetILGenerator();
				if (!disabledMethods.Contains(removeMethod))
				{
					ilGenerator.Emit(OpCodes.Ldarg_0);
					ilGenerator.Emit(OpCodes.Ldfld, inner);
					ilGenerator.Emit(OpCodes.Ldarg_1);
					ilGenerator.Emit(OpCodes.Callvirt, removeMethod);
					ilGenerator.Return();
				}
				else
					ilGenerator.ThrowException(typeof(InvalidOperationException), errorMessage);
				eb.SetRemoveOnMethod(methodBuilder);
			}

			return Activator.CreateInstance(typeBuilder.CreateType(), obj, disabledMethods) as T;
		}
		/// <summary>
		/// Disables specified methods on an instance.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="obj">The actual instance to create a proxy from.</param>
		/// <param name="methodNames">Methods to disable.</param>
		/// <returns>Returns a proxy instance that does not allow to invoke the specified methods.</returns>
		public static T Disable<T>(T obj, IEnumerable<string> methodNames) where T : class
		{
			return Disable<T>(obj, typeof(T).GetMethods().Where(m => methodNames.Contains(m.Name)));
		}
	}
}